<template>
  <view class="calculator">
    <view class="input-group">
      <input type="number" v-model.number="num1" placeholder="输入第一个数字" />
      <input type="number" v-model.number="num2" placeholder="输入第二个数字" />
    </view>
    <view class="buttons">
      <button @click="calculate('add')">加法</button>
      <button @click="calculate('sub')">减法</button>
      <button @click="calculate('mul')">乘法</button>
      <button @click="calculate('div')">除法</button>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    // 可以通过props设置默认操作类型
    defaultOperation: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      num1: 0,
      num2: 0
    }
  },
  methods: {
    calculate(operation) {
      let result;
      switch(operation) {
        case 'add':
          result = this.num1 + this.num2;
          break;
        case 'sub':
          result = this.num1 - this.num2;
          break;
        case 'mul':
          result = this.num1 * this.num2;
          break;
        case 'div':
          result = this.num2 !== 0 ? this.num1 / this.num2 : '除数不能为0';
          break;
        default:
          result = '请选择操作';
      }
      // 触发自定义事件，将结果传递给父组件
      this.$emit('calculated', {
        operation,
        num1: this.num1,
        num2: this.num2,
        result
      });
    }
  },
  mounted() {
    // 如果有默认操作，自动计算
    if (this.defaultOperation) {
      this.calculate(this.defaultOperation);
    }
  }
}
</script>
<style>
.calculator {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin: 20px;
  width: calc(100% - 40px); /* 确保不超出屏幕 */
}

.input-group {
  margin-bottom: 15px;
  width: 100%;
}

.input-group input {
  border: 1px solid #ddd;
  padding: 12px 15px; /* 增加内边距 */
  margin: 8px 0; /* 适当外边距 */
  width: 100%;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, 
               Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  font-size: 16px;
  height: 48px; /* 固定高度 */
  line-height: 24px; /* 确保文字垂直居中 */
  min-width: 0; /* 解决flex布局可能的问题 */
}

/* 确保按钮不会挤压输入框 */
.buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 10px; /* 使用gap替代margin */
}

.buttons button {
  flex: 1 1 45%;
  min-width: 0; /* 重要：防止按钮挤压 */
  padding: 12px;
  font-size: 14px;
}
</style>